<?php
/**
 * Created by PhpStorm.
 * User: junyv
 * Date: 2016/9/18
 * Time: 11:52
 */

namespace app\manage\controller;
class SecondHouse extends Base
{
    //前置操作定义
    protected $beforeActionList = [
        'beforeEdit'  =>  ['only'=>'edit'],
        'getPosition' =>  ['only'=>['edit','add']]
    ];
    private $mod;
    private $area;
    private $model;
    public function _initialize(){
        parent::_initialize();
        $this->mod = model('second_house');
        $this->list_field = 'id,area_name,title,img,rec_position,estate_name,total_price,create_time,status,ordid';
        $this->sort = 'ordid';
        $this->order = 'asc,id desc';
        $this->model = 'second_house';
    }
    //搜索
    public function _search(){
        $map = array();
        $time_start = input('get.time_start');
        $time_end = input('get.time_end');
        if($time_start && !$time_end){
            $map['create_time'] = ['egt',strtotime($time_start)];
        }elseif($time_end && $time_end){
            $map['create_time'] = ['between',[strtotime($time_start),strtotime($time_end)+86399]];
        }
        ($keyword = input('get.keyword')) && $map['title'] = ['like', '%'.$keyword.'%'];
        $status = -1;
        if(isset($_GET['status']) && $_GET['status'] !== ''){
            $status = input('get.status/d');
        }
        $status>=0 && $map['status'] = ['eq',$status];
        $spid = '';
        $area         = input('get.area');
        if(strpos($area,',')!==FALSE){
            $area_arr    = explode(',',$area);
            $map['area'] = $area_arr[1];
            $spid        = str_replace(',','|',$area);
        }elseif(!empty($area)){
            $map['city'] = $area;
            $spid        = $area;
        }
        $this->assign('search', array(
            'time_start' => $time_start,
            'time_end' => $time_end,
            'selected_ids' => $spid,
            'status'  => $status,
            'keyword' => $keyword
        ));
        return $map;
    }
    public function addDo(){
        \app\common\model\SecondHouse::event('before_insert',function($obj){
            $city = cache('city');
            if($obj->area){
                $area_arr  = explode(',',$obj->area);
                $map       = explode(',',input('post.map'));
                $obj->lat  = isset($map[1])?$map[1]:0;
                $obj->lng  = isset($map[0])?$map[0]:0;
                $obj->city = $area_arr[0];
                $obj->city_name = $city['cate'][$area_arr[0]]['name'];
                $obj->area      = isset($area_arr[1])?$area_arr[1]:0;
                $obj->area_name = isset($area_arr[1])?$city['cate'][$area_arr[1]]['name']:'';
                $obj->house_type         = implode(',',$obj->house_type);
                $obj->peitao    = isset($obj->peitao)?implode(',',$obj->peitao):'';
            }
            if(!isset($obj->seo_title)){
                $obj->seo_title = $obj->title;
            }
            if(empty($obj->seo_keys)){
                $obj->seo_keys = $this->setSeo(['title'=>$obj->estate_name]);
            }
            $images = $this->getPic();
            if($images){
                $obj->file = $images;
            }
            if(!isset($_POST['position'])){
                $obj->rec_position = 0;
            }else{
                $obj->rec_position = 1;
            }
            return true;
        });
        \app\common\model\SecondHouse::event('after_insert',function($obj){
           $obj->estate_id > 0 && model('estate')->where(['id'=>$obj->estate_id])->setInc('second_num');
            $this->addPosition($obj->id);//添加推荐位
        });
        parent::addDo();
    }
    public function editDo(){
        \app\common\model\SecondHouse::event('before_update',function($obj){
            $city = cache('city');
            if($obj->area){
                $area_arr  = explode(',',$obj->area);
                $map       = explode(',',input('post.map'));
                $obj->lat  = isset($map[1])?$map[1]:0;
                $obj->lng  = (isset($map[0]) && !empty($map[0]))?$map[0]:0;
                $obj->city = $area_arr[0];
                $obj->city_name = $city['cate'][$area_arr[0]]['name'];
                $obj->area      = isset($area_arr[1])?$area_arr[1]:0;
                $obj->area_name = isset($area_arr[1])?$city['cate'][$area_arr[1]]['name']:'';
                $obj->house_type= implode(',',$obj->house_type);
                $obj->peitao    = isset($obj->peitao)?implode(',',$obj->peitao):'';
            }
            $images = $this->getPic();
            if($images){
                $obj->file = $images;
            }
            if(!isset($_POST['position'])){
                $obj->rec_position = 0;
            }else{
                $obj->rec_position = 1;
            }
            return true;
        });
        \app\common\model\SecondHouse::event('after_update',function($obj){
            $userid = isset($obj->user_id) ? $obj->user_id : 0;
            $this->sendSysMsg($obj->title,$userid,$obj->status);
            $this->addPosition($obj->id);//添加、修改推荐位
        });
        parent::editDo();
    }
    public function delete(){
        //删除后置操作
        \app\common\model\SecondHouse::event('after_delete',function($obj){
            model('estate')->where(['id'=>$obj->estate_id,'second_num'=>['gt',0]])->setDec('second_num');
            //删除推荐二手房数据
            action('Position/deleteByHouseId',['house_id'=>$obj->id,'model'=>$this->model],'controller');
        });
        parent::delete();
    }
    /**
     * @param $obj
     * 添加图片
     */
    private function getPic(){
        $insert = [];
        if(isset($_POST['pic']) && !empty($_POST['pic'])) {
            $images = $_POST['pic'];
            foreach ($images['pic'] as $key => $v) {
                $insert[] = [
                    'url' => $v,
                    'title' => $images['alt'][$key],
                ];
            }
        }
        return $insert;
    }
    /**
     * 获取推荐位和小区
     */
    public function getPosition(){
        $where['model'] = $this->model;
        $pos_list = model('position_cate')->where($where)->field('id,title')->select();
        $estate_list = model('estate')->where(['status'=>1])->field('id,title')->select();
        $this->assign('estate_list',$estate_list);
        $this->assign('pos_list',$pos_list);
    }
    //把房源添加到推荐位中
    private function addPosition($id){
        $position   = input('post.position/a');//新选择的推荐位id
        $exists_pos = input('post.exists_pos');//原推荐位id
        $exists_pos_arr = [];
        $exists_pos && $exists_pos_arr = explode(',',$exists_pos);
        $add = [];$del  = [];
        if($position && $exists_pos_arr){
            foreach($position as $v){
                if(!in_array($v,$exists_pos_arr)){
                    //新增
                    $add[] = $v;
                }
            }
            foreach($exists_pos_arr as $v){
                if(!in_array($v,$position)){
                    //删除
                    $del[] = $v;
                }
            }
        }elseif($position && !$exists_pos){
            $add = $position;
        }elseif(!$position && $exists_pos){
            $del = $exists_pos_arr;
        }
        if($del){
            model('position')->where(['house_id'=>$id,'model'=>$this->model,'cate_id'=>['in',$del]])->delete();
            model('position_cate')->where(['id'=>['in',$del],'num'=>['gt',0]])->setDec('num');
        }
        if($add){
            action('Position/addPosition',['model'=>$this->model,'ids'=>$id,'cate_id'=>$add],'controller');//添加推荐位
        }

    }
    //编辑前置操作
    public function beforeEdit(){
        $id = input('param.id/d',0);
        if($id){
            $pos_id = model('position')->where(['house_id'=>$id,'model'=>$this->model])->column('cate_id');//获取该小区所属的推荐位id
            $this->assign('pos_id',$pos_id);
        }else{
            $this->error('参数错误');
        }
    }
    //异步获取小区信息
    public function getEstateInfo(){
        $id = input('get.id/d',0);
        $return['status'] = 0;
        if($id){
            $info = model('estate')->where(['id'=>$id])->field('title,lat,lng,niandai,address')->find();
            if($info){
                $info['map'] = $info['lng'].','.$info['lat'];
                $return['status'] = 1;
                $return['data']   = $info;
            }
        }
        return json($return);
    }
    /**
     * 异步检查房源是否存在
     */
    public function ajaxCheckTitle(){
        $title = input('get.J_title');
        $id    = input('param.id/d',0);
        $return['status'] = 1;
        $where['title'] = $title;
        $id && $where['id'] = ['neq',$id];
        $count = $this->mod->where($where)->count();
        if($count > 0){
            $return['status'] = 0;
        }
        return json($return);
    }

    //关键词设置
    private function setSeo($data){
        $seo_keys = "title,title二手房,title价格";
        $seo_keys = str_replace('title',$data['title'],$seo_keys);
        return $seo_keys;
    }
    private function sendSysMsg($title,$userid,$status=1){
        if($userid){
            switch($status){
                case 0:
                    $str = '您发布的二手房【'.$title.'】被管理员转为审核状态';
                    break;
                case 1:
                    $str = '您发布的二手房【'.$title.'】已通过管理员审核';
                    break;
                case 2:
                    $str = '您发布的二手房【'.$title.'】未通过管理员审核,请编辑后再提交';
                    break;
                default:
                    $str = '您发布的二手房【'.$title.'】已通过管理员审核';
                    break;
            }
            $data['type']    = 2;
            $data['gid']     = $userid;
            $data['title']   = '二手房审核通知';
            $data['content'] = $str;
            model('sysmessage')->save($data);
        }

    }
}